package com.zhangqi.zhxa.base.impl.menudetail;

import android.app.Activity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.viewpagerindicator.CirclePageIndicator;
import com.zhangqi.zhxa.R;
import com.zhangqi.zhxa.base.BaseMenuDetailPager;
import com.zhangqi.zhxa.domain.NewsData;
import com.zhangqi.zhxa.domain.NewsMenuData;
import com.zhangqi.zhxa.global.Constants;
import com.zhangqi.zhxa.utils.CacheUtils;
import com.zhangqi.zhxa.view.RefreshListView;

import java.util.ArrayList;

/**
 * 12个页签的页面对象--新闻页面
 * @author ZhangQi
 * @date 2016-5-2
 *
 */
public class TabDetailPager extends BaseMenuDetailPager {

    private NewsMenuData.NewsTabData mTabData;//页签分类的网络信息
    private NewsData mNewsTabData;//网络返回的新闻列表数据
    private String mUrl;//加载新闻列表的url

    //头条新闻的网络数据
    private ArrayList<NewsData.TopNews> mTopNewsList;
    //头条新闻的数据适配器
    private TopNewsAdapter mTopNewsAdapter;
    //新闻列表ListView集合
    private ArrayList<NewsData.News> mNewsList;

    private NewsAdapter mNewsAdapter;

    @ViewInject(R.id.vp_tab_detail)
    private com.zhangqi.zhxa.view.HorizontalScrollViewPager mViewPager;

    @ViewInject(R.id.lv_tab_detail)
    private RefreshListView lvList;

    @ViewInject(R.id.indicator)
    private CirclePageIndicator mIndicator;

    @ViewInject(R.id.tv_title)
    private TextView tvTopNewsTitle;




    public TabDetailPager(Activity activity,NewsMenuData.NewsTabData tabData) {
        super(activity);
        mTabData = tabData;
        mUrl = Constants.SERVER_URL+mTabData.url;
    }

    @Override
    public View initView() {
       /* mTextView = new TextView(mActivity);
        //view.setText(mTabData.title);
        mTextView.setTextColor(Color.RED);
        mTextView.setTextSize(22);
        mTextView.setGravity(Gravity.CENTER);*/

        //View view = View.inflate(mActivity, R.layout.pager_menu_detail_news,null);
        View view = View.inflate(mActivity, R.layout.pager_tab_detail,null);
        ViewUtils.inject(this,view);

        View header = View.inflate(mActivity,R.layout.list_header_topnews,null);
        ViewUtils.inject(this,header);//必须也将头布局注入到viewutils,才能初始化成功
        //给listView添加头布局
        lvList.addHeaderView(header);

        //设置下拉刷新的监听
        lvList.setOnRefreshLishListener(new RefreshListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //从网络加载数据
                getDataFromService();
            }
        });
        return view;
    }


    @Override
    public void initData() {
        //mTextView.setText(mTabData.title);
        String cache = CacheUtils.getCache(mUrl,mActivity);
        if(!TextUtils.isEmpty(cache)){
            processResult(cache);


        }

        getDataFromService();
    }

    public void getDataFromService() {
        HttpUtils utils = new HttpUtils();
        utils.send(HttpRequest.HttpMethod.GET, mUrl, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                processResult(result);

                Log.i("fff", "--------------------------------------访问网络成功");

                CacheUtils.setCache(mUrl, result, mActivity);//写入缓存
                //收起下拉刷新控件
                lvList.onRefreshComplete();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                //收起下拉刷新控件
                lvList.onRefreshComplete();
                e.printStackTrace();
                Toast.makeText(mActivity,s,Toast.LENGTH_LONG).show();

            }
        });
    }

    private void processResult(String result) {
        Gson gson = new Gson();
        mNewsTabData = gson.fromJson(result, NewsData.class);
        //Log.i("dd","解析结果---------------------------"+newsData);

        //初始化头条新闻
        mTopNewsList = mNewsTabData.data.topnews;
        if(mTopNewsList!=null){
            mTopNewsAdapter = new TopNewsAdapter();
            mViewPager.setAdapter(mTopNewsAdapter);
            mIndicator.setViewPager(mViewPager);//将指示器和viewpager绑定
            mIndicator.setSnap(true);//快照模式，设置圆点一跳一跳


            mIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    Log.i("WW", "--position-----------------------" + position);
                    NewsData.TopNews topNews = mTopNewsList.get(position);
                    tvTopNewsTitle.setText(topNews.title);
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });

            mIndicator.onPageSelected(0);//将小圆点的位置归0，解决他会在页面时仍记录上次位置的bug
            tvTopNewsTitle.setText(mTopNewsList.get(0).title);//初始化第一页标题

        }

        //初始化新闻列表
        mNewsList = mNewsTabData.data.news;
        if(mNewsList!=null){
            mNewsAdapter = new NewsAdapter();
            lvList.setAdapter(mNewsAdapter);
        }

    }

    class NewsAdapter extends BaseAdapter{

        public BitmapUtils mBitmapUtils;
        public NewsAdapter(){
            mBitmapUtils = new BitmapUtils(mActivity);
            mBitmapUtils.configDefaultLoadingImage(R.drawable.topnews_item_default);
        }


        @Override
        public int getCount() {
            return mNewsList.size();
        }

        @Override
        public NewsData.News getItem(int position) {
            return mNewsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if(convertView==null){
                convertView =View.inflate(mActivity,R.layout.list_item_news,null);
                holder = new ViewHolder();
                holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
                holder.tvDate = (TextView) convertView.findViewById(R.id.tv_date);
                holder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();

            }

            NewsData.News news = getItem(position);
            holder.tvTitle.setText(news.title);
            holder.tvDate.setText(news.pubdate);
            //-------修改ip-----------
            //获取图片连接，使用链接下载图片，将图片设置给ImageView,考虑内存溢出问题，图片本地缓存
            String imageUrl = news.listimage;
            String s = imageUrl.substring(26);//为了换成自己的ip
            String imgsurl = Constants.SERVER_URL+s;

            mBitmapUtils.display(holder.ivIcon,imgsurl);

            return convertView;
        }
    }

    static class ViewHolder{
        public TextView tvTitle;
        public TextView tvDate;
        public ImageView ivIcon;

    }


    class TopNewsAdapter extends PagerAdapter{

        //xUtils框架中BitmapUtils帮助类
        BitmapUtils mBitmapUtils;

        public TopNewsAdapter() {
           // 初始化xutils中的加载图片的工具
           mBitmapUtils = new BitmapUtils(mActivity);
           // 设置默认加载图片
           mBitmapUtils.configDefaultLoadingImage(R.drawable.topnews_item_default);
        }

        @Override
        public int getCount() {
            return mTopNewsList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView view = new ImageView(mActivity);
            //获取图片连接，使用链接下载图片，将图片设置给ImageView,考虑内存溢出问题，图片本地缓存
            String imagesUrl = mTopNewsList.get(position).topimage;

            String substring = imagesUrl.substring(26);//为了换成自己的ip
            String imgurl = Constants.SERVER_URL+substring;

            view.setScaleType(ImageView.ScaleType.FIT_XY);//设置图片填充效果，表示填充父窗体

            mBitmapUtils.display(view, imgurl);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }
}
